package com.zhangyu.shadow.repair.delegate.search;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.Group;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zhangyu.shadow.repair.R;
import com.zhangyu.shadow.repair.R2;
import com.zhangyu.shadow.repair.config.RepairItemType;
import com.zhangyu.shadow.repair.delegate.bean.BusBean;
import com.zhangyu.shadow.repair.delegate.bean.BusTypeBean;
import com.zhangyu.shadow.repair.delegate.maintain.MaintainDelegate;
import com.zhangyu.shadow.repair.delegate.repair.RepairDelegate;
import com.zhangyu.shadow.repair.event.ViewPagerClickEvent;
import com.zhangyu.shadow.repair.manager.AccountManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import st.lib.base.delegate.mvp.MvpDelegate;
import st.lib.base.ui.datepicker.DateUtils;
import st.lib.base.ui.progress.sweetalert.DialogLoader;
import st.lib.base.ui.progress.sweetalert.IDialogClickListener;
import st.lib.base.ui.recycler.BaseDecoration;
import st.lib.base.ui.recycler.MultipleItemEntity;

/**
 * @author zhangyu
 * @date 2018/2/11
 */

public class SearchBusDelegate extends MvpDelegate<SearchBusPresenter> implements SearchBusContract.View {

    private static final String DELEGATE_FROM = "delegate_from";

    public static SearchBusDelegate create(int fromId) {
        final SearchBusDelegate contentDelegate = new SearchBusDelegate();
        final Bundle bundle = new Bundle();
        bundle.putInt(DELEGATE_FROM, fromId);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @BindView(R2.id.toolbar_search)
    Toolbar mToolbar;
    @BindView(R2.id.et_search)
    EditText mEditTextSearch;
    @BindView(R2.id.tabs)
    TabLayout mTabs;
    @BindView(R2.id.viewpager)
    ViewPager mViewpager;
    @BindView(R2.id.group)
    Group mGroupData;
    @BindView(R2.id.tv_refresh)
    TextView mTvRefresh;
    @BindView(R2.id.list_view_search_bus)
    RecyclerView mRecyclerView;
    private SearchPagerAdapter mPagerAdapter;

    private int mIdFrom = 0;
    private List<TabFragment> mFragments = new ArrayList<>();
    private List<BusTypeBean> mTitles = new ArrayList<>();
    private String mCurrentDate;
    private SearchDataAdapter mSearchDataAdapter;

    private DialogLoader mDialogLoader;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        final Bundle bundle = getArguments();
        if (bundle != null) {
            mIdFrom = bundle.getInt(DELEGATE_FROM);
        }
    }

    @OnClick(R2.id.btn_reset)
    public void onViewClicked() {
        search();
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_search_bus;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        initView();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        EventBus.getDefault().register(this);
        initData();
    }

    private void initData() {
        setData();
        getBusList();
    }

    /**
     * 初始化数据
     */
    private void setData() {
        mCurrentDate = DateUtils.getNowCalendar(0);
        mPagerAdapter = new SearchPagerAdapter(getChildFragmentManager(), mFragments, mTitles);
        mViewpager.setAdapter(mPagerAdapter);
        mSearchDataAdapter = new SearchDataAdapter(getContext(), null);
        mSearchDataAdapter.setEmptyView(R.layout.view_list_empty, (ViewGroup) mRecyclerView.getParent());
        mRecyclerView.setAdapter(mSearchDataAdapter);
        mSearchDataAdapter.bindToRecyclerView(mRecyclerView);
        mSearchDataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MultipleItemEntity item = (MultipleItemEntity) adapter.getItem(position);
                if ((item != null ? item.getItemType() : 0) == RepairItemType.ITEM_TYPE_REPAIR) {
                    start(RepairDelegate.create(item));
                } else {
                    start(MaintainDelegate.create(item));
                }
            }
        });
    }

    private void initView() {
        if (mDialogLoader == null) {
            mDialogLoader = new DialogLoader(getContext());
        }
        mEditTextSearch.setHint("请输入车辆编号");
        mEditTextSearch.setInputType(InputType.TYPE_CLASS_NUMBER);
        mEditTextSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    search();
                    return true;
                }
                return false;
            }
        });
        initToolbarNav(mToolbar);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(BaseDecoration.create(_mActivity.getResources()
                .getColor(R.color.color_white), 1));
    }

    protected void initToolbarNav(Toolbar toolbar) {
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int i = item.getItemId();
                if (i == R.id.menu_search) {
                    search();
                }
                return true;
            }
        });
        toolbar.inflateMenu(R.menu.search);
    }

    private void search() {
        if (mEditTextSearch.getText().toString().length() == 0) {
            getBusList();
        } else {
            mPresenter.searchCode(mEditTextSearch.getText().toString());
        }

    }

    private void getBusList() {
        mPresenter.getBusList(mCurrentDate,
                DateUtils.getSpecifiedDayAfter(mCurrentDate, 1),
                AccountManager.getInstance().getDepId());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void pagerAdapterClick(ViewPagerClickEvent event) {
        final BusBean bean = event.getBusBean();
        mPresenter.searchBus(bean.getVehicleCode() + "");
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Override
    public SearchBusPresenter getPresenter() {
        return new SearchBusPresenter(this);
    }

    @Override
    public void getBusListSuccess(List<BusTypeBean> list) {
        for (int i = 0, size = list.size(); i < size; i++) {
            BusTypeBean typeBean = list.get(i);
            if (mFragments.size() >= i + 1) {
                TabFragment tabFragment = mFragments.get(i);
                tabFragment.dataChanged(typeBean.getBeanList());
                mTitles.set(i, typeBean);
            } else {
                mFragments.add(TabFragment.newInstance(typeBean.getBeanList()));
                mTabs.addTab(mTabs.newTab().setText(typeBean.getName()));
                mTitles.add(typeBean);
            }
        }
        mPagerAdapter.notifyDataSetChanged();
        mTabs.setupWithViewPager(mViewpager);
        mViewpager.setOffscreenPageLimit(list.size());
        showBusListData();
    }

    @Override
    public void getBusListFailed(int code, String msg) {
        showLoadError(msg);
    }

    @Override
    public void searchCodeSuccess(ArrayList<MultipleItemEntity> list) {
        if (list.size() > 0) {
            mSearchDataAdapter.setNewData(list);
            showSearchListData();
        } else {
            showSearchEmpty();
        }
    }

    @Override
    public void searchCodeFailed(int code, String msg) {
        showLoadError(msg);
    }

    @Override
    public void searchBusSuccess(ArrayList<MultipleItemEntity> list) {
        closeDialogProgress();
        if (list.size() > 0) {
            MultipleItemEntity item = list.get(0);
            if ((item != null ? item.getItemType() : 0) == RepairItemType.ITEM_TYPE_REPAIR) {
                start(RepairDelegate.create(item));
            } else {
                start(MaintainDelegate.create(item));
            }
        } else {
            mDialogLoader.showFailed("提示", "该车辆无保养计划", new IDialogClickListener() {
                @Override
                public void onClick() {
                    mDialogLoader.clearDialog();
                }
            });
        }
    }

    @Override
    public void searchBusFailed(int code, String msg) {
        mDialogLoader.showFailed("提示", msg, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
            }
        });
    }

    @Override
    public void showDialogProgress() {
        mDialogLoader.showProgressDialog(false, "提示", "正在加载...");
    }

    @Override
    public void closeDialogProgress() {
        mDialogLoader.clearDialog();
    }

    @Override
    public void showLoading(String str) {
        showRefresh();
    }

    @Override
    public void hideLoading() {

    }

    private void showRefresh() {
        mTvRefresh.setVisibility(View.VISIBLE);
        mTvRefresh.setText("正在加载,请稍候...");
        mGroupData.setVisibility(View.GONE);
        mRecyclerView.setVisibility(View.GONE);
    }

    private void showLoadError(String msg) {
        mTvRefresh.setVisibility(View.VISIBLE);
        mTvRefresh.setText(String.format("加载失败,%s,刷新试试!", msg));
        mGroupData.setVisibility(View.GONE);
        mRecyclerView.setVisibility(View.GONE);
    }

    private void showBusListData() {
        mTvRefresh.setVisibility(View.GONE);
        mGroupData.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
    }

    private void showSearchListData() {
        mTvRefresh.setVisibility(View.GONE);
        mGroupData.setVisibility(View.GONE);
        mRecyclerView.setVisibility(View.VISIBLE);
    }

    private void showSearchEmpty() {
        mTvRefresh.setVisibility(View.VISIBLE);
        mTvRefresh.setText("该车辆无保养计划");
        mGroupData.setVisibility(View.GONE);
        mRecyclerView.setVisibility(View.GONE);
    }
    @Override
    public boolean onBackPressedSupport() {
        if (!isFastClick()) {
            pop();
        }
        return true;
    }

}
